package com.wjb.xietong.W3;

import java.util.Map;
import org.json.JSONObject;
import android.content.Context;
import android.graphics.Bitmap;
import android.widget.ImageView;
import com.wjb.xietong.Volley.Request;
import com.wjb.xietong.Volley.RequestQueue;
import com.wjb.xietong.Volley.Response;
import com.wjb.xietong.Volley.VolleyError;
import com.wjb.xietong.Volley.toolbox.ImageLoader;
import com.wjb.xietong.Volley.toolbox.ImageLoader.ImageCache;
import com.wjb.xietong.Volley.toolbox.ImageLoader.ImageListener;
import com.wjb.xietong.Volley.toolbox.ImageRequest;
import com.wjb.xietong.Volley.toolbox.Volley;
import com.wjb.xietong.component.AppGlobal;
import com.wjb.xietong.util.IDs;
import com.wjb.xietong.util.LogD;

public class HttpUtil {

	private static final String BASE_URL = "http://work.wangjubao.com/work/";

	private static RequestQueue mRequestQueue;

	public static void init(Context context) {
		mRequestQueue = Volley.newRequestQueue(context);
	}
	
	public static int post(String url, Map<String, String> params,
			final JsonHttpResponseHandler responseHandler) {
		return post(url, params, responseHandler, true);
	}

	public static int post(String url, Map<String, String> params,
			final JsonHttpResponseHandler responseHandler, boolean shouldCache) {

		LogD.output("URL:" + BASE_URL + url);
		LogD.output("Param:" + (params == null ? null : params.toString()));
		PostRequest jr = new PostRequest(Request.Method.POST, BASE_URL + url,
				params, new Response.Listener<JSONObject>() {
					@Override
					public void onResponse(JSONObject response) {
						LogD.output("Response:"
								+ (response == null ? null : response
										.toString()));

						if (null != responseHandler) {
							responseHandler.onSuccess(response);
						}
					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						LogD.output("onErrorResponse:" + error.getMessage());
						if (null != responseHandler) {
							if (null != error.networkResponse) {
								responseHandler.onFailure(
										error.networkResponse.statusCode,
										error, null);
							} else {
								responseHandler.onFailure(
										IDs.HTTP_STATUS_ERROR_500, error, null);
							}
						}
					}
				});
		jr.setShouldCache(shouldCache);// 是否需要缓存
		addRequestQueue(jr);
		return IDs.REQUEST_OK;

	}

	private static boolean addRequestQueue(Request<?> request) {
		if (null != mRequestQueue) {
			mRequestQueue.add(request);
			return true;
		}
		init(AppGlobal.getInstance().getContext());
		if (null != mRequestQueue) {
			mRequestQueue.add(request);
			return true;
		}
		return false;
	}
}
